package meterMonitor.util;

import meterMonitor.constand.APIConsts;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

@Service
public class BizUtil {
    public static final Logger logger = LoggerFactory.getLogger(BizUtil.class);

    @Autowired
    protected ResourceConfig resourceConfig;

    public String GetDayOrNight() {
        String configTime = GetDayIntervalTime();
        String[] arrays = configTime.split("-");

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String nowTime = sdf.format(new Date());
        if (arrays[0].compareTo(arrays[1]) < 0) {
            if (nowTime.compareToIgnoreCase(arrays[0]) >= 0 && nowTime.compareToIgnoreCase(arrays[1]) < 0) {
                return APIConsts.DayCode;
            } else {
                return APIConsts.NightCode;
            }
        } else {
            if (nowTime.compareToIgnoreCase(arrays[0]) >= 0 || nowTime.compareToIgnoreCase(arrays[1]) < 0) {
                return APIConsts.DayCode;
            } else {
                return APIConsts.NightCode;
            }
        }
    }

    /**
     * @return 白班间隔毫秒数
     */
    public Long GetDayClassSeconds() {
        String configTime = GetDayIntervalTime();
        String[] arrays = configTime.split("-");

        return GetSecondsBetweenTime(arrays[0], arrays[1]);
    }

    /**
     * @return 晚班间隔毫秒数
     */
    public Long GetNightClassSeconds() {
        String configTime = GetNightIntervalTime();
        String[] arrays = configTime.split("-");

        return GetSecondsBetweenTime(arrays[0], arrays[1]);
    }

    /**
     * 本班已消逝的时间
     *
     * @return 本班已消逝的时间
     * (现在 - 本班开始)秒数
     */
    public Integer GetSecondsConsumedOfCurrentShift() {
        String configTime = GetDayIntervalTime();
        String[] arrays = configTime.split("-");
        Date now = new Date();
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
        Date start_time = meterMonitor.util.DateUtils.parse(sdfDate.format(now) + " " + arrays[0], "yyyy-MM-dd HH:mm");
        Date end_time = meterMonitor.util.DateUtils.parse(sdfDate.format(now) + " " + arrays[1], "yyyy-MM-dd HH:mm");
        //
        if (start_time.after(end_time)) {
            end_time = meterMonitor.util.DateUtils.addDays(end_time, 1);
        }
        //
        if (now.after(start_time) && now.before(end_time)) {
            //当前是白班
            return meterMonitor.util.DateUtils.getOffsetSeconds(start_time, now);
        } else if (now.after(end_time)) {
            //当前过了白班
            return meterMonitor.util.DateUtils.getOffsetSeconds(end_time, now);
        } else { //if (now.before(start_time))
            //当前还不到白班
            Date last_start = meterMonitor.util.DateUtils.addDays(end_time, -1);
            return meterMonitor.util.DateUtils.getOffsetSeconds(last_start, now);
        }
    }

    /**
     * @param timeFrom 时间开始字串，格式：HH:mm
     * @param timeTo   时间结束字串，格式：HH:mm
     * @return
     */
    public Long GetSecondsBetweenTime(String timeFrom, String timeTo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String nowDate = GetNowDate();
        Date fromTime = null, toTime = null;
        try {
            fromTime = sdf.parse(nowDate + " " + timeFrom);
            toTime = sdf.parse(nowDate + " " + timeTo);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (toTime.before(fromTime)) {
            DateUtils.addDays(toTime, 1);
        }

        return (toTime.getTime() - fromTime.getTime()) / 1000;
    }

    public String GetDayIntervalTime() {
        return resourceConfig.getValueByKey("day_interval_time");
    }

    public String GetNightIntervalTime() {
        return resourceConfig.getValueByKey("day_interval_time");
    }

    public Integer GetIntervalSecondsMonitorPage() {
        String str = resourceConfig.getValueByKey("monitor_page_refresh_interval");
        Integer i = 5;
        try {
            i = Integer.valueOf(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (i == null) {
            i = 5;
        }
        return i;
    }

    public String GetNowTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

    public String GetNowDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }

    private Date getCouldShowDateTime(){
        String str = "720";
        Integer min = 720;
        try {
            str = resourceConfig.getValueByKey("interval_minutes");
            min = Integer.valueOf(str);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        Date date = meterMonitor.util.DateUtils.addMinutes(new Date(), -min);
        return date;
    }

    //取多少分钟之前的时间
    public String getCouldShowDate() {
        Date date = getCouldShowDateTime();
        String beforStr = getOwnDate(date);
        return beforStr;
    }

    public String getCouldShowBanci(){
        Date date = getCouldShowDateTime();
        String beforStr = getOwnBanci(date);
        return beforStr;
    }

    //根据所给日期自定义给出所属日期
    protected String getOwnDate(Date uploadTime) {
        String dayIntervalTime = GetDayIntervalTime();
        String[] dayArr = dayIntervalTime.split("-");
        String[] startTime = dayArr[0].split(":");
        int startHour = Integer.parseInt(startTime[0]);
        int startMin = Integer.parseInt(startTime[1]);
        Calendar ca = Calendar.getInstance();
        ca.setTime(uploadTime);
        int mqHour = ca.get(Calendar.HOUR_OF_DAY);
        int mqMin = ca.get(Calendar.MINUTE);

        int startTotalMin = startHour * 60 + startMin;
        int mqTotalMin = mqHour * 60 + mqMin;
        if (mqTotalMin < startTotalMin) {
            Date d = DateUtils.addDays(uploadTime, -1);
            return DateFormatUtils.format(d, meterMonitor.util.DateUtils.PATTERN_CLASSICAL_SIMPLE);
        }
        return DateFormatUtils.format(uploadTime, meterMonitor.util.DateUtils.PATTERN_CLASSICAL_SIMPLE);
    }

    public String getOwnBanci(Date uploadTime){
        String dayIntervalTime = GetDayIntervalTime();
        String[] dayArr = dayIntervalTime.split("-");
        //
        String[] startTime = dayArr[0].split(":");
        int startHour = Integer.parseInt(startTime[0]);
        int startMin = Integer.parseInt(startTime[1]);
        int startTotalMin = startHour * 60 + startMin;
        //
        String[] endTime = dayArr[1].split(":");
        int endHour = Integer.parseInt(endTime[0]);
        int endMin = Integer.parseInt(endTime[1]);
        int endTotalMin =endHour*60+endMin;
        //
        Calendar ca = Calendar.getInstance();
        ca.setTime(uploadTime);
        int mqHour = ca.get(Calendar.HOUR_OF_DAY);
        int mqMin = ca.get(Calendar.MINUTE);
        int mqTotalMin = mqHour * 60 + mqMin;
        //
        if (startTotalMin < endTotalMin){
            //班次开始时间 < 班次结束时间
            if (mqTotalMin >= startTotalMin && mqTotalMin <= endTotalMin){
                //白班
                return APIConsts.DayCode;
            } else {
                //晚班
                return APIConsts.NightCode;
            }
        } else {
            //班次开始时间 > 班次结束时间
            if (mqTotalMin >= startTotalMin || mqTotalMin <= endTotalMin){
                //白班
                return APIConsts.DayCode;
            } else {
                //晚班
                return APIConsts.NightCode;
            }
        }
    }

    public String GetYestorday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date time = cal.getTime();
        return sdf.format(time);
    }

    public Date GetYestordayDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date time = cal.getTime();
        return time;
    }

    public String Round(Double d, int digits) {
        NumberFormat nf = NumberFormat.getNumberInstance();

        // 保留两位小数
        nf.setMaximumFractionDigits(2);

        // 如果不需要四舍五入，可以使用RoundingMode.DOWN
        nf.setRoundingMode(RoundingMode.UP);

        return nf.format(digits);
    }

    public Double GetThresholdRecRate() {
        String str = resourceConfig.getValueByKey("threshold_rec_rate");
        Double d = 0.4;
        try {
            d = Double.valueOf(str);
        } catch (Exception e) {

        }
        return d;
    }

    public Integer GetThresholdGiantDataCount() {
        String str = resourceConfig.getValueByKey("threshold_giant_data_count");
        Integer i = 3;
        try {
            i = Integer.valueOf(str);
        } catch (Exception e) {

        }
        return i;
    }

    public Integer GetThresholdNegtiveDataCount() {
        String str = resourceConfig.getValueByKey("threshold_negtive_data_count");
        Integer i = 3;
        try {
            i = Integer.valueOf(str);
        } catch (Exception e) {

        }
        return i;
    }

    public Double GetThresholdBatteryCapacity() {
        String str = resourceConfig.getValueByKey("threshold_battery_capacity");
        Double i = 10d;
        try {
            i = Double.valueOf(str);
        } catch (Exception e) {

        }
        return i;
    }

    /**
     * 获取当前月最大天数
     *
     * @return 天数
     */
    public static int getDayOfMonth() {
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int day = aCalendar.getActualMaximum(Calendar.DATE);
        return day;
    }

    /**
     * 获取本月开始日期
     *
     * @return String
     **/
    public static String getMonthStart() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }

    /**
     * 获取上月最后日期
     *
     * @return String
     **/
    public static String getMonthStartE() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 0);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }

    /**
     * 获取上月开始日期
     *
     * @return String
     **/
    public static String getMonthStartK() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }

    /**
     * 获取本月最后一天
     *
     * @return String
     **/
    public static String getMonthEnd() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }

    /**
     * 获取本周的第一天
     *
     * @return String
     **/
    public static String getWeekStart() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.WEEK_OF_MONTH, 0);
        cal.set(Calendar.DAY_OF_WEEK, 2);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }

    /**
     * 获取本周的最后一天
     *
     * @return String
     **/
    public static String getWeekEnd() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK));
        cal.add(Calendar.DAY_OF_WEEK, 1);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }

    /**
     * 获取本年的第一天
     *
     * @return String
     **/
    public static String getYearStart() {
        return new SimpleDateFormat("yyyy").format(new Date()) + "-01-01";
    }

    /**
     * 获取本年的最后一天
     *
     * @return String
     **/
    public static String getYearEnd() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, calendar.getActualMaximum(Calendar.MONTH));
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date currYearLast = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(currYearLast);
    }

}
